package com.dm.action;

import com.dm.common.Const;
import com.dm.dto.FolderAttributeDto;
import com.dm.dto.ResponseDto;
import com.dm.dto.input.FolderDto;
import com.dm.service.FolderService;
import com.dm.utils.JsonDateValueProcessor;
import com.dm.utils.JsonRequestDataUtil;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * @author hqw521@qq.com
 * @date 2018/11/12 21:34
 */
@Namespace("/dm/folder")
@ParentPackage("json-default")
@Results({@Result(name = "jsonData", type = "json", params = {"root", "jsonData"})})
public class FolderAction extends ActionSupport {
    private String jsonData;

    public String getJsonData() {
        return jsonData;
    }

    public void setJsonData(String jsonData) {
        this.jsonData = jsonData;
    }

    @Autowired
    private FolderService folderService;

    @Action("findFolders")
    public String findFolders() {
        JSONObject jsonObject = JsonRequestDataUtil.getJsonRequestData(ServletActionContext.getRequest());
        Integer userId = jsonObject.getInt("userId");
        JSONArray jsonArray = JSONArray.fromObject(folderService.findFolders(userId));
        jsonData = jsonArray.toString();
        return Const.JSON;
    }

    @Action("addFolder")
    public String addFolder() {
        FolderDto folderDto = (FolderDto) JsonRequestDataUtil.getBean(ServletActionContext.getRequest(), FolderDto.class);
        ResponseDto responseDto = folderService.addFolder(folderDto);
        jsonData = JSONObject.fromObject(responseDto).toString();
        return Const.JSON;
    }

    @Action("folderRename")
    public String folderRename() {
        FolderDto folderDto = (FolderDto) JsonRequestDataUtil.getBean(ServletActionContext.getRequest(), FolderDto.class);
        ResponseDto responseDto = folderService.folderRename(folderDto.getFolderName(), folderDto.getFolderId());
        jsonData = JSONObject.fromObject(responseDto).toString();
        return Const.JSON;
    }
    @Action("findFolderAttribute")
    public String findFolderAttribute() {
        JSONObject jsonObject = JsonRequestDataUtil.getJsonRequestData(ServletActionContext.getRequest());
        Integer folderId = (Integer) jsonObject.get("folderId");
        ResponseDto<FolderAttributeDto> responseDto = folderService.findFolderAttribute(folderId);
        JsonConfig jsonConfig = new JsonConfig();
        // 将自定已的date转换器注册进去
        jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
        jsonData = JSONObject.fromObject(responseDto, jsonConfig).toString();
        return Const.JSON;
    }
}
